<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>气象图切换演示</title>
    <script src="../libs/Cesium/Cesium.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/geotiff@2.0.7/dist-browser/geotiff.js"></script>
    <link href="../libs/Cesium/Widgets/widgets.css" rel="stylesheet">
    <style>
        #cesium_container {
            width: 100%;
            height: 100vh;
            margin: 0;
            padding: 0;
        }
        .coordinate-display {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: rgba(255,255,255,0.9);
            padding: 10px 15px;
            border-radius: 4px;
            font-family: Arial, sans-serif;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div id="cesium_container"></div>
    <div class="coordinate-display">
        经度: <span id="lon-value">-</span><br>
        纬度: <span id="lat-value">-</span>
    </div>
    
    <!-- 新增底图切换按钮 -->
    <button id="toggleBasemap" style="position: absolute; top: 20px; right: 60px; z-index: 1000; padding: 10px; background: rgba(255,255,255,0.9); border: 1px solid #ddd; border-radius: 4px; cursor: pointer;">
        切换湿度底图
    </button>

    <script>
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNTliNDE3MC05NDE0LTRhOTMtODIwYi0yZjMxZjVlZjNkMDIiLCJpZCI6MjkwMTk0LCJpYXQiOjE3NDc2MzYwMTV9.SPGLHdzH1zgco8PydI7KBFEsIsmicw8ZFw4gE3Ch-8w';

        // 初始化Viewer时禁用默认底图
        const viewer = new Cesium.Viewer('cesium_container', {
            animation: false,
            baseLayerPicker: false,  // 禁用默认底图选择器
            fullscreenButton: false,
            timeline: false,
            homeButton: false,
            sceneModePicker: true,
            navigationHelpButton: false,
            geocoder: false,
            infoBox: false,
            selectionIndicator: false
        });

        // 允许加载本地文件
        Cesium.DeveloperError.throwOnError = false;
        viewer.allowDataSourcesToSuspendAnimation = false;
        viewer.resolutionScale = 0.5;

        // 添加增强版底图切换功能
        const toggleBtn = document.getElementById('toggleBasemap');
        let tiffLayer = null;
        const proxyCanvas = document.createElement('canvas');
        
        async function loadGeoTIFF() {
            try {
                // 使用相对路径并通过服务器访问
                const response = await fetch('../../data/data_humidity_925hpa_2018-12-01.tif', {
                    mode: 'cors',
                    headers: {'Content-Type': 'image/tiff'},
                    cache: 'no-cache'
                });
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                const arrayBuffer = await response.arrayBuffer();
                const tiff = await GeoTIFF.fromArrayBuffer(arrayBuffer);
                const image = await tiff.getImage();
                
                // 设置canvas尺寸
                proxyCanvas.width = image.getWidth();
                proxyCanvas.height = image.getHeight();
                const ctx = proxyCanvas.getContext('2d');
                
                // 读取栅格数据
                const raster = await image.readRasters();
                const imageData = ctx.createImageData(proxyCanvas.width, proxyCanvas.height);
                
                // 数据预处理：增强可视化效果
                // 优化大数据处理
                const rawData = new Uint16Array(raster[0]);
                
                // 更安全的最小最大值计算
                let min = Infinity, max = -Infinity;
                for(let i = 0; i < rawData.length; i++) {
                    if(rawData[i] < min) min = rawData[i];
                    if(rawData[i] > max) max = rawData[i];
                }
                
                // 简化的颜色映射
                const range = max - min;
                // 使用Web Worker处理大数据
                const worker = new Worker('js/tiff-worker.js');
                worker.postMessage({
                    rawData: rawData.buffer,
                    min,
                    max,
                    width: proxyCanvas.width,
                    height: proxyCanvas.height
                }, [rawData.buffer]);

                worker.onmessage = (e) => {
                    ctx.putImageData(e.data.imageData, 0, 0);
                    console.log('Web Worker处理完成', {
                        processingTime: e.data.processingTime + 'ms',
                        memoryUsage: e.data.memoryUsage
                    });
                    
                    // 创建Cesium图像层
                    tiffLayer = viewer.imageryLayers.addImageryProvider(
                        new Cesium.SingleTileImageryProvider({
                            url: proxyCanvas.toDataURL(),
                            rectangle: Cesium.Rectangle.fromDegrees(
                                Math.max(-180, image.getBoundingBox().minX),
                                Math.max(-90, image.getBoundingBox().minY),
                                Math.min(180, image.getBoundingBox().maxX),
                                Math.min(90, image.getBoundingBox().maxY)
                            ),
                            tilingScheme: new Cesium.GeographicTilingScheme()
                        })
                    );
                };
                
                console.log('TIFF数据范围:', {min, max});
                console.log('Canvas尺寸:', proxyCanvas.width, 'x', proxyCanvas.height);
                
                ctx.putImageData(imageData, 0, 0);
                
                // 创建Cesium图像层
                return new Cesium.SingleTileImageryProvider({
                    url: proxyCanvas.toDataURL(),
                    rectangle: Cesium.Rectangle.fromDegrees(
                        image.getBoundingBox().minX, 
                        image.getBoundingBox().minY,
                        image.getBoundingBox().maxX,
                        image.getBoundingBox().maxY
                    )
                });
            } catch (error) {
                console.error('TIFF加载失败:', error);
                alert(`湿度数据加载失败: ${error.message}`);
                return null;
            }
        }

        toggleBtn.addEventListener('click', async function() {
            if (!tiffLayer) {
                const provider = await loadGeoTIFF();
                if (provider) {
                    tiffLayer = viewer.imageryLayers.addImageryProvider(provider);
                    toggleBtn.textContent = '恢复默认底图';
                }
            } else {
                viewer.imageryLayers.remove(tiffLayer);
                tiffLayer = null;
                toggleBtn.textContent = '切换湿度底图';
            }
        });

        // 去除Cesium logo
        viewer._cesiumWidget._creditContainer.style.display = "none";

        // 切换到2D平面模式
        viewer.scene.mode = Cesium.SceneMode.SCENE2D;       

        // 设置俯视视角（-90度俯角）
        viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(117.134, 32.726, 10000000),
          orientation: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-90),
            roll: 0
          }
        });


        // 坐标显示功能
        const lonSpan = document.getElementById('lon-value');
        const latSpan = document.getElementById('lat-value');
        const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        
        handler.setInputAction(function(movement) {
            const position = viewer.scene.camera.pickEllipsoid(movement.endPosition);
            if (position) {
                const cartographic = Cesium.Cartographic.fromCartesian(position);
                lonSpan.textContent = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4);
                latSpan.textContent = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4);
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        

        
    </script>
</body>
</html>
